import ProLayout, { DefaultFooter } from '@ant-design/pro-layout';
import React, { useMemo } from 'react';
import logo from '@/assets/logo.svg';
import { connect, Link } from 'umi';
import { Helmet, HelmetProvider } from 'react-helmet-async';
import RightContent from '@/components/GlobalHeader/RightContent';
import { getMatchMenu, transformRoute } from '@umijs/route-utils';
import Authorized, { checkAuthority } from '@/components/Authorized';
import { Result } from 'antd';

const BasicLayout = (props) => {
  const { children, route, settings, login } = props;

  const {
    loginUser: { authority: currentAuthority },
  } = login;

  const menuDataRender = (menuList) =>
    menuList.map((item) => {
      const localItem = {
        ...item,
        children: item.children ? menuDataRender(item.children) : undefined,
      };
      return checkAuthority(item.authority, currentAuthority) ? localItem : null;
    });

  const defaultFooter = <DefaultFooter copyright={settings.copyright} links={null} />;

  const breadcrumbRender = (routers = []) => [
    {
      path: '/',
      breadcrumbName: '首页',
    },
    ...routers,
  ];

  const authorized = useMemo(
    () =>
      getMatchMenu(
        window.location.pathname || '/',
        transformRoute(route.routes).menuData,
      ).pop() || { authority: undefined },
    [window.location.pathname],
  );

  const noMatch = <Result status="403" title="403" subTitle="抱歉，您没有权限访问该页面" />;

  return (
    <HelmetProvider>
      <Helmet>
        <title>{settings.title}</title>
      </Helmet>
      <ProLayout
        logo={logo}
        {...settings}
        menuItemRender={(menuItemProps, defaultDom) => {
          if (window.location.pathname === menuItemProps.path) {
            return defaultDom;
          }
          return <Link to={menuItemProps.path}>{defaultDom}</Link>;
        }}
        footerRender={() => defaultFooter}
        rightContentRender={() => <RightContent />}
        breadcrumbRender={breadcrumbRender}
        menuDataRender={menuDataRender}
        route={route}
      >
        {/* <Authorized authority={authorized.authority} noMatch={noMatch}> */}
        {children}
        {/* </Authorized> */}
      </ProLayout>
    </HelmetProvider>
  );
};

export default connect(({ settings, login }) => ({ settings, login }))(BasicLayout);
